#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/8 12:42
# @Author  : youfeng

import paramiko


class Sftp(object):
    def __init__(self, host, port, user, password, log):
        self.log = log
        self.__transport = paramiko.Transport((host, port))
        self.__transport.connect(username=user, password=password)
        self.__sftp = paramiko.SFTPClient.from_transport(self.__transport)
        self.log.info("登录信息: host:{} port:{} user:{} password:{}".format(
            host, port, user, password))
        # 将location.py 上传至服务器 /tmp/test.py
        # __sftp.put('fromlinux.txt', '/tmp/test_from_win')
        # 将remove_path 下载到本地 local_path
        # __sftp.get('/root/oldgirl.txt', 'fromlinux.txt')

    def __del__(self):
        self.close()

    def close(self):
        if self.__sftp is not None:
            self.__sftp.close()
            self.__sftp = None
        if self.__transport is not None:
            self.__transport.close()
            self.__transport = None

    def mkdir(self, remote_path):
        if self.__sftp is None:
            return

        try:
            self.__sftp.mkdir(remote_path)
        except Exception as e:
            self.log.error("创建目录失败: ")
            self.log.exception(e)

    def put(self, local_path, remote_path):
        if self.__sftp is None:
            return False

        try:
            # self.log.info("当前路径: dir = {}".format(self.__sftp.getcwd()))
            self.__sftp.put(local_path, remote_path)
            self.log.info('[+] 上传成功:' + local_path + ' -> ' + remote_path)
        except Exception as e:
            self.log.error('[+] 上传失败:' + local_path + ' -> ' + remote_path + ' because ' + str(e))
            self.log.exception(e)
            return False
        return True
